package com.lxl.microservicesimpleprovideruser.service;

import com.lxl.microservicesimpleprovideruser.bean.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import rx.Observable;

import javax.annotation.Resource;

/**
 * @desc: (用户)聚合 service
 * @date & @author: 2018/11/29 16:39 & lxl
 */
@Service
public class AggregationServcie {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 从用户微服务获得用户
     *
     * @param id 用户id
     * @return Observable
     */
    @HystrixCommand(fallbackMethod = "userFallback")
    public Observable<User> getUserById(long id) {
        // 创建一个被观察者
        return Observable.create(observer -> {
            User user = restTemplate.getForObject("http://microservice-provider-user-my-metadata/{id}", User.class, id);
            observer.onNext(user);
            observer.onCompleted();
        });
    }

    @HystrixCommand(fallbackMethod = "userFallback")
    public Observable<User> getMovieUserByUserId(long id) {
        return Observable.create(observer -> {
            User user = restTemplate.getForObject("http://consumer-movie-ribbon-hystrix/user/{id}", User.class, id);
            observer.onNext(user);
            observer.onCompleted();
        });
    }


    /**
     * 回退方法
     *
     * @param id 用户id
     * @return User
     */
    public User userFallback(long id) {
        User user = new User();
        user.setId(id);
        user.setName("我是zuul聚合时的回退方法");
        return user;
    }
}
